package com.cxm.qyyz.base.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.bumptech.glide.Glide;
import com.cxm.qyyz.R;
import com.cxm.qyyz.base.mvp.BaseContract;
import com.cxm.qyyz.utils.AppUtil;
import com.cxm.qyyz.widget.plus.StatusBarPlus;
import com.trello.rxlifecycle4.LifecycleTransformer;
import com.trello.rxlifecycle4.android.ActivityEvent;


import java.util.Objects;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import per.goweii.anylayer.AnyLayer;
import per.goweii.anylayer.Layer;
import per.goweii.anylayer.dialog.DialogLayer;

public abstract class BaseActivity<T extends BaseContract.BasePresenter> extends PermissionActivity<T> {

    private Unbinder unbinder;
    protected Activity mActivity;
//    private StatePlus statePlus;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        //设置屏幕方向
        setScreenOrientation();
        super.onCreate(savedInstanceState);
        //在绑定布局之前
        initBeforeBindLayout();
        //引用布局
        View rootView = LayoutInflater.from(this).inflate(getLayoutId(), null, false);
        if (supportStateController()) {
            rootView.setTag("ContentView");
//            statePlus = new StatePlus();
//            statePlus.setOnStateControllerListener(new StatePlus.OnStateControllerListener() {
//                @Override
//                public void onStateController(int itemType) {
//                    if (itemType == StatePlus.ERROR) {
//                        onReload();
//                    }
//                }
//            });
//            rootView = statePlus.init(rootView);
        }
        setContentView(rootView);
        //引用
        mActivity = this;
        //Activity管理类
        AppUtil.getInstance().push(this);
        //ButterKnife
        unbinder = ButterKnife.bind(this);
        //注册EventBus
        if (supportEventBus()) {
            registerEventBus();
        }
        //适配状态栏
        initStatusBar();
        initTitle();
        //初始化操作
        initEvents();
    }

    void initTitle() {
        TextView tvAction = findViewById(R.id.tvAction);
        if (null != tvAction)
            tvAction.setText(getTitles());
        View ivBack = findViewById(R.id.ivBack);
        if (null != ivBack) ivBack.setOnClickListener(v -> finish());
    }

    public String getTitles() {
        return getTitle().toString();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseEvents();
        if (supportEventBus()) {
            unregisterEventBus();
        }
        unbinder.unbind();
        AppUtil.getInstance().pop(mActivity);
    }

    protected void releaseEvents() {
        onData();
        onDismiss();
    }

    @LayoutRes
    protected abstract int getLayoutId();

    protected abstract void initEvents();

    protected void initBeforeBindLayout() {

    }

    protected boolean supportEventBus() {
        return false;
    }

    protected void registerEventBus() {
    }

    protected void unregisterEventBus() {
    }

    protected void setScreenOrientation() {
//        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }

    protected void initStatusBar() {
        StatusBarPlus.setColor(this, getResources().getColor(R.color.color_ffffff), true);
        StatusBarPlus.setStatusBarMode(this, true);
    }

    protected boolean supportStateController() {
        return true;
    }

    @Override
    public void toast(String message) {
        AppUtil.getInstance().showToast(message);
        dismiss();
    }

    @Override
    public void toast(int resId) {
        AppUtil.getInstance().showToast(resId);
        dismiss();
    }

    @Override
    public void onData() {
    }

    @Override
    public void onLoad() {
    }

    @Override
    public void onShow() {
        showDialog();
    }

    @Override
    public void onDismiss() {
        dismiss();
    }

    @Override
    public void onError() {
        dismiss();
    }

    @Override
    public void onReload() {

    }

    @Override
    public void jumpToLogin() {

    }

    @Override
    public <E> LifecycleTransformer<E> bindToLife() {
        return this.bindUntilEvent(ActivityEvent.DESTROY);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();      //得到当前页面的焦点,ps:有输入框的页面焦点一般会被输入框占据
            if (isShouldHideKeyboard(v, ev)) { //判断用户点击的是否是输入框以外的区域
                hideKeyboard(v);   //收起键盘
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    private boolean isShouldHideKeyboard(View v, MotionEvent event) {
        if (v instanceof EditText) {  //判断得到的焦点控件是否EditText
            int[] l = {0, 0};
            v.getLocationInWindow(l);//得到输入框在屏幕中上下左右的位置
            int left = l[0], top = l[1], bottom = top + v.getHeight(), right = left + v.getWidth();
            if (event.getX() > left && event.getX() < right && event.getY() > top && event.getY() < bottom) {
                // 点击位置如果是EditText的区域，忽略它，不收起键盘。
                return false;
            } else {
                v.clearFocus();
                return true;
            }
        }
        // 如果焦点不是EditText则忽略
        return false;
    }

    protected void hideKeyboard(View view) {
        InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (im != null) {
            im.hideSoftInputFromWindow(view.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    DialogLayer dialogLayer;

    /**
     * dialog
     * date 2021/12/20
     * author yzx
     */
    public void showDialog() {
    }

    /**
     * 取消弹框
     * date 2021/12/20
     * author yzx
     */
    public void dismiss() {
        if (null != dialogLayer) {
            dialogLayer.dismiss(false);
        }
    }

    //全局定义
    private long lastClickTime = 0L;
    // 两次点击间隔不能少于1000ms
    private static final int FAST_CLICK_DELAY_TIME = 1000;


    public void onClick(View view) {
        if (System.currentTimeMillis() - lastClickTime < FAST_CLICK_DELAY_TIME) {
            return;
        }
        lastClickTime = System.currentTimeMillis();
        onClicks(view);
    }

    public void onClicks(View view) {
    }
    private boolean isFirstRender = true;
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus && isFirstRender){
            isFirstRender = false;
            onRenderFinish();
        }
    }

    public void onRenderFinish(){}
}
